import base64
import hashlib
import logging
import traceback
from flask import request
from flask_restful import Resource
from sqlalchemy import text

from app.commons.redis_session import redis_con
from app.models.admin.admin import UserInfo
from app.models.admin.token_info import TokenInfo
from app.commons.db import db
import time


class LoginView(Resource):

    def post(self):

        try:
            recv_data = request.get_json()
            username = recv_data["username"]
            password = recv_data["password"]
            r=redis_con()
            password_hash=r.get("user-%s"%username)
            if not password_hash:
                user = UserInfo.query.filter_by(user_name=username).first()
                # 后续可返回状态码
                if username is None or password is None:
                    return {"err_msg": "param invalid"}
                if user is None:
                    return {"err_msg": "user not existed"}
                password_hash=user.password_hash
            # 移除了加密
            if password_hash == hashlib.sha256(password.encode("utf-8")).hexdigest():
                current_time = int(time.time())
                token = "%s_%s" % (username, current_time)
                logging.warning("create token for user=%s,token=%s" % (username, token))
                return {"success": "true", "token": token}
            else:
                return {"success": "false"}
        except Exception as e:
            traceback.print_exc()
            return {"exception": "true"}
